<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\components\PHPZip;
use common\components\Upload;
use common\models\business\BusinessContractCategory;
use common\models\business\BusinessContractField;
use common\models\business\BusinessContractFieldvalue;
use Yii;
use common\models\business\BusinessContract;
use backend\modules\business\models\BusinessContractSearch;
use yii\db\Query;
use yii\helpers\FileHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ContractController implements the CRUD actions for BusinessContract model.
 */
class ContractController extends AdminController
{
    public $enableCsrfValidation  = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessContract models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessContractSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessContract model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $showpre = BusinessContractCategory::showPre(BusinessContractCategory::findOne($model->cateid));


        return $this->render('view', [
            'model' => $this->findModel($id),
            'showpre' => $showpre
        ]);
    }

    /**
     * Creates a new BusinessContract model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessContract();
        $cateid = Yii::$app->request->get('cateid');
        if(empty($cateid)){
            $cate = BusinessContractCategory::find()->asArray()->one();
            $cateid = $cate['id'];
        }
        $model->cateid = $cateid;
        $showpre = BusinessContractCategory::showPre(BusinessContractCategory::findOne($cateid));

        $postdata = Yii::$app->request->post();
        if ($model->load($postdata)) {

            if(false !== $photo = Upload::upload($model,'afile')){
                $model->setAttribute('afile',$photo);
            }
            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }

            $contractid = Yii::$app->db->getLastInsertID();


            foreach ($postdata as $key => $value){
                $fid = (new Query())->select('id')->from(BusinessContractField::tableName())->where('name=:name',[':name'=>$key])->one();
                if($fid){
                    $data = [
                        'contractid' =>$contractid,
                        'fieldid' => $fid['id'],
                        'value' => $value
                    ];
                    Yii::$app->db->createCommand()->insert(BusinessContractFieldvalue::tableName(),$data)->execute();
                }
            }
            return $this->redirect(['view', 'id' => $model->id]);

        } else {
            $model->name = BusinessContractCategory::findOne($cateid)->title;
            return $this->render('create', [
                'model' => $model,
                'showpre' =>$showpre,
            ]);
        }
    }

    /**
     * Updates an existing BusinessContract model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $postdata = Yii::$app->request->post();

        if ($model->load($postdata)) {
            $model->setScenario('update');
            foreach ($postdata as $key => $value){
                $fid = (new Query())->select('id')->from(BusinessContractField::tableName())->where('name=:name',[':name'=>$key])->one();
                if($fid){
                    $ise = Yii::$app->db->createCommand('select id from '.BusinessContractFieldvalue::tableName().' where contractid=:id and fieldid=:fid')
                        ->bindValues([':id'=>$id,':fid'=>$fid['id']])->queryOne();
                    $data = [
                        'contractid' => $id,
                        'fieldid' => $fid['id'],
                        'value' => $value
                    ];
                    if(!$ise){
                        Yii::$app->db->createCommand()->insert(BusinessContractFieldvalue::tableName(),$data)->execute();
                    }else{
                        Yii::$app->db->createCommand()->update(BusinessContractFieldvalue::tableName(),$data,'contractid=:id and fieldid=:fid',[':id'=>$id,':fid'=>$fid['id']])
                            ->execute();
                    }
                }
            }

            if (false !== $afile = Upload::upload($model, 'afile')) {
                $model->setAttribute('afile', $afile);
            }

            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }else {
            $showpre = BusinessContractCategory::showPre(BusinessContractCategory::findOne($model->cateid));
            $model->start_time = date('Y-m-d',$model->start_time);
            $model->end_time = date('Y-m-d',$model->end_time);
            return $this->render('update', [
                'model' => $model,
                'showpre' => $showpre
            ]);
        }
    }

    /**
     * Deletes an existing BusinessContract model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }


    /**
     * 下载附件
     */
//    public function actionDownattch($id)
//    {
//        $file = BusinessContract::find()->select('afile')->from(BusinessContract::tableName())->where('id=:id',[':id'=>$id])->asArray()->one();
//        $files = Upload::checkGetPath($file['afile']);
//
//        foreach ($files as $key => $row){
//            $content =  file_get_contents($row);
//            return Yii::$app->response->sendContentAsFile($content,$row);
//        }
//
//
//    }




    /**
     * Finds the BusinessContract model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessContract the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessContract::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
